package com.xie.authority_system.utils;

import com.xie.authority_system.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.ConstructorBinding;
import org.springframework.security.core.userdetails.UserDetails;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 谢金成
 * @date 2024/1/9 9:23
 */
@Data
@NoArgsConstructor
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {
//    /**
//     * 密钥
//     */
//    private String secret;

    /**
     * 过期时间: 毫秒
     */
    private Long expiration;

    /**
     * 对密钥加密
     */
    private SecretKey key = null;


    @ConstructorBinding
    public JwtUtils(/*String secret, */Long expiration) {
        //this.secret = secret;
        this.expiration = expiration;
        key = Jwts.SIG.HS512.key().build();
    }

    /**
     * 从数据声明中生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().claims(claims).expiration(expirationDate).signWith(key, Jwts.SIG.HS512).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims getClaimsFormToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload();
        } catch (Exception e) {
            claims = null;
        }

        return claims;
    }

    /**
     * @param userDetails
     * @return
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put(Claims.SUBJECT, userDetails.getUsername());
        claims.put(Claims.ISSUED_AT, new Date());
        return generateToken(claims);
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFormToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }

        return username;
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(String token) {
        Claims claims = getClaimsFormToken(token);
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 刷新令牌
     *
     * @param token 令牌
     * @return 新令牌
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFormToken(token);
            HashMap<String, Object> newClaims = new HashMap<>();
            claims.forEach((k, v)->{
                newClaims.put(k, v);
            });
            newClaims.put(Claims.ISSUED_AT, new Date());
            refreshedToken = generateToken(newClaims);
        } catch (Exception e) {
            refreshedToken = null;
        }

        return refreshedToken;
    }

    /**
     * 验证令牌
     *
     * @param token       令牌
     * @param userDetails 用户
     * @return 是否有效
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        User user = (User) userDetails;
        String username = getUsernameFromToken(token);
        return (username.equals(user.getUsername()) && !isTokenExpired(token));
    }
}
